package se.zens.demo.wsapp.implementation.exchangerates;

import java.math.BigDecimal;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import se.zens.demo.wsapp.configuration.WSAppConfiguration;
import se.zens.demo.wsapp.implementation.AbstractWSAppProcessor;
import se.zens.demo.wsapp.implementation.exceptions.InvalidCurrencyException;
import se.zens.demo.wsapp.interfaces.WSAppResultCodes;
import se.zens.demo.wsapp.interfaces.model.ConvertAmountRequest;
import se.zens.demo.wsapp.interfaces.model.ConvertAmountResponse;
import se.zens.demo.wsapp.interfaces.model.ExchangeRate;

public class ConvertAmountProcessor extends AbstractWSAppProcessor
{
	private static Logger logger = LogManager
			.getLogger(ConvertAmountProcessor.class);
	private ConvertAmountRequest request;
	private ConvertAmountResponse response;
	private Map<String, ExchangeRate> currentExchangeRates;

	public ConvertAmountProcessor(WSAppConfiguration config,
			ConvertAmountRequest request,
			Map<String, ExchangeRate> currentExchangeRates)
	{
		this.request = request;
		this.currentExchangeRates = currentExchangeRates;
		this.response = new ConvertAmountResponse(request);

	}

	public void process()
	{
		try
		{
			if (request.getAmount() == null || request.getAmount().compareTo(BigDecimal.ZERO ) < 0)
			{
				response.setResultCode(WSAppResultCodes.INVALID_AMOUNT);
				return;
			}	
			if (currentExchangeRates == null || currentExchangeRates.isEmpty())
			{
				response.setResultCode(WSAppResultCodes.EXCHANGERATE_NOT_FOUND);
				return;
			}
			
			String key = getCurrencyPairKey(request.getFromCurrency(),
					request.getToCurrency());

			ExchangeRate rate = currentExchangeRates.get(key);

			response.setRate(rate);
			if (rate == null)
			{
				response.setResultCode(WSAppResultCodes.EXCHANGERATE_NOT_FOUND);
				return;
			}
			response.setConvertedAmount(request.getAmount().multiply(rate.getRate()));
			response.setResultCode(WSAppResultCodes.SUCCESS);
			response.setResultMessage("SUCCESS");

		} catch (InvalidCurrencyException ex)
		{
			this.response.setResultCode(WSAppResultCodes.INVALID_CURRENCY);
			this.response.setResultMessage(ex.getMessage());
		}

	}

	public ConvertAmountResponse getResponse()
	{
		return response;
	}
}
